package com.example.demo.Interceptor;
import com.example.demo.model.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;



//定义拦截器
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("目标方法前执行");
        HttpSession session = request.getSession(false);
        if(session==null){
            response.setStatus(401);  //这里必须的设置响应的一个状态码，return false
            return false;
        }
        User user = (User) session.getAttribute("user");
        if(user==null||user.getId()<=0){
            response.setStatus(401);
            return false;   //false会进行拦截
        }
        return true; //true表示放行
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        log.info("目标方法后执行");
    }


}